package com.yc.http.d0703;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 响应对象
 */
public class HttpServletResponse {

    private final OutputStream outputStream;
    private int status;
    private String msg;
    private String contentType;
    // 输出缓冲区
    CharArrayWriter buffer = new CharArrayWriter();  // 资源流
    PrintWriter printWriter =  new PrintWriter(buffer);  // 处理流

    public HttpServletResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    // 返回打印字符流
    public PrintWriter getWriter() {
        return printWriter;
    }

    // 设置结果码
    public void setStatus(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    // set响应内容类型
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    // 托送响应报文
    public void flushBuffer() throws IOException {
        // 响应头行
        outputStream.write(("HTTP/1.1 " + status + " " + msg + "\n").getBytes(StandardCharsets.UTF_8));
        // 响应头域参数
        outputStream.write(("Content-Type: " + contentType + "\n").getBytes(StandardCharsets.UTF_8));
        // 空行
        outputStream.write(("\n").getBytes(StandardCharsets.UTF_8));
        // Body
        outputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
    }

    public int getStatus() {
        return status;
    }

    public String getContentType() {
        return contentType;
    }
}
